// ignore: implementation_imports, import_of_legacy_library_into_null_safe
import 'package:build/src/builder/build_step.dart';
import 'package:analyzer/dart/element/element.dart' as ele;

// ignore: import_of_legacy_library_into_null_safe
import 'package:source_gen/source_gen.dart';

// ignore: import_of_legacy_library_into_null_safe
import 'package:build/build.dart';
import 'dart:io';
import 'tpl/tpl.dart' as tpl;
import 'api.dart';

class ApiGenerator extends GeneratorForAnnotation<GApi> {
  final separator = Platform.pathSeparator;

  @override
  generateForAnnotatedElement(
      ele.Element element, ConstantReader annotation, BuildStep buildStep) {
    var enable = false;
    try {
      enable = annotation.read('enable').boolValue;
    } catch (e) {}
    if (!enable) return null;
    var package = buildStep.inputId.package;
    var directory =
        Directory('${Directory.current.path}${separator}lib${separator}api');
    if (!directory.existsSync()) {
      tpl.Tpl.buildCode.forEach((info) {
        var filePath =
            '${Directory.current.path}${separator}lib$separator${info.filePath}';
        File(filePath)
          ..createSync(recursive: true)
          ..writeAsStringSync(info.codeBuild(package: package));
      });
    }
    return null;
  }
}

Builder apiBuilder(BuilderOptions options) =>
    LibraryBuilder(ApiGenerator(), generatedExtension: ".api.dart");
